﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Globalization;
using System.Reflection;
using AkazoNobel.Scheduler.Core;
using AkazoNobel.Scheduler.StoreMasterData.Common;
using AkazoNobel.Scheduler.StoreMasterData.DataAccess;
using AkazoNobel.Scheduler.StoreMasterData.DataAccess.Model;
using AkazoNobel.Scheduler.StoreMasterData.DataAccess.Service;
using AkazoNobel.Ultimus.Extension;
using Dapper;
using Quartz;
using Ultimus.OC;
using Ultimus.WFServer;

namespace AkazoNobel.Scheduler.StoreMasterData.Tasks
{
    public class StoreMasterDataSync : BaseTask
    {
        //#region 原版本
        //    public override void ExecuteTask(IJobExecutionContext context)
        //    {

        //        AssessmentService.GetLastLikeKey("NS");
        //        //1.从E-Approve数据库中抓取新审批通过的数据。
        //        var tintings = TintingService.GetList();

        //        using (var conn = SqlConnectionHelper.GetConnection(Constant.MDC_DB_NAME))
        //        {
        //            foreach (var tinting in tintings)
        //            {
        //                //格式化省份格式，去掉“省”，“市”， “自治区”
        //                tinting.ProvinceName = tinting.ProvinceName.Replace("省", "").Replace("市", "").Replace("自治区", "");


        //                //2.根据不同的申请类型发起不同的流程
        //                if (tinting.NewFitmentName.Contains("关店") || tinting.NewFitmentName.Contains("降级")) //发起主数据变更流程
        //                {
        //                    if (string.IsNullOrEmpty(tinting.CertiCode)) //授权号不能为空
        //                    {
        //                        Logger.Debug("授权号不能为空！[" + tinting.ShopName + tinting.InstanceGuid + "]");
        //                        continue;
        //                    }

        //                    DegradeStore(tinting);
        //                }
        //                else //发起新门店流程
        //                {
        //                    if (tinting.ApplicationTypeName == "无需机器" && tinting.MachineDeposit > 0)
        //                    {
        //                        Logger.Debug("[" + tinting.SerialNumber + "]的申请类型为“无需机器”，但是设备保证金金额为" +
        //                                     tinting.MachineDeposit);
        //                        continue;
        //                    }
        //                    NewStore(tinting);
        //                }
        //            }

        //        }
        //    }

        //    /// <summary>
        //    ///  申请人WinId转换 EApprove中的格式是
        //    ///  cn=dengj11,cn=organizational users,o=AkzoNobel,cn=cordys,o=apac.ad.ici.com，
        //    ///  需要转换成 apac.ad.ici.com/dengj11
        //    /// </summary>
        //    /// <param name="code"></param>
        //    /// <returns></returns>
        //    public string GetWinId(string code)
        //    {
        //        const string defaultAccount = "d30.intra/svc_dpcna_mdc";
        //        if (string.IsNullOrEmpty(code)) //发起人不能为空
        //        {
        //            return defaultAccount;
        //        }
        //        try
        //        {
        //            var arrStrings = code.Split(',');
        //            var winId = arrStrings[arrStrings.Length - 1].Split('=')[1] + '/' + arrStrings[0].Split('=')[1];

        //            //查询OC里面有没有此帐号
        //            var oc = new OrgChart();
        //            User ocUser;

        //            return (oc.FindUser(winId, "", 0, out ocUser)) ? winId : defaultAccount;
        //        }
        //        catch (Exception ex)
        //        {
        //            Logger.Error(ex);
        //            return defaultAccount;
        //        }
        //    }

        //    /// <summary>
        //    /// 门店降级关闭
        //    /// </summary>
        //    /// <param name="tinting"></param>
        //    public void DegradeStore(Tinting tinting)
        //    {
        //        var variables = new List<Variable>();
        //        var applicationNo = "";
        //        var incident = 0;
        //        var winId = GetWinId(tinting.CreatorEmpDN);

        //        // 匹配EP与SMD中的授权号命名规则
        //        if (!tinting.CertiCode.StartsWith("A")) tinting.CertiCode = "A" + tinting.CertiCode;

        //        var smdStore = SmdStoreService.GetByAuthId(tinting.CertiCode);
        //        if (smdStore == null)
        //        {
        //            Logger.Debug("授权号错误，找不到相应门店数据！[" + tinting.CertiCode + "]");
        //            return;
        //        }

        //        //发起流程
        //        variables.AddRange(MdcRecipientService.SetStoreDataChangeRecipient(tinting.AreaName, tinting.ProvinceName, "Store"));
        //        variables.Add("BlankVlue", smdStore.StoreID);
        //        variables.Add("Actions", "DegradeStore");
        //        variables.Add("AutoBusinessKey", "DegradeStore");
        //        variables.Add("MailSubject", smdStore.StoreName);


        //        incident = TaskHelper.NewIncident(winId, "Store Data Change",
        //            tinting.NewFitmentName + " - " + tinting.ShopName, variables, out applicationNo);

        //        //获取first Task
        //        var taskFirstData = TaskHelper.GetTask("Store Data Change", incident, new[] { winId }, "Fill in the request");

        //        #region 绑定业务数据

        //        if (incident == 0 || taskFirstData == null) //流程发起失败
        //        {
        //            Logger.Debug("主数据变更流程发起失败！[" + tinting.InstanceGuid + "]");
        //            return;
        //        }

        //        using (var conn = SqlConnectionHelper.GetConnection(Constant.MDC_DB_NAME))
        //        {
        //            var trans = conn.BeginTransaction();
        //            try
        //            {
        //                #region  写入业务数据

        //                var ass = TaskHelper.SetAssessment(winId, taskFirstData.strProcessName, incident,
        //                    taskFirstData.strStepName, "DegradeStore", conn, trans);

        //                var storeTypeCode = SmdStoreService.GetStoreTypeCode(tinting.ShopTypeName);

        //                var store = new Store
        //                {
        //                    SubmitDate = tinting.SubmitDate,
        //                    Creator = winId,
        //                    CreatorStaffCode = tinting.CreatorEmpCode,
        //                    SerialNumber = tinting.SerialNumber,
        //                    DealerName = tinting.CustomerName,
        //                    DealerCode = tinting.CustomerCode,
        //                    StoreType = storeTypeCode,
        //                    StoreName = tinting.ShopName,
        //                    ApplicationType = tinting.ApplicationTypeName,
        //                    NewFitment = tinting.NewFitmentName,
        //                    Fax = tinting.Fax,
        //                    Telephone = tinting.Telephone,
        //                    ContractPerson = tinting.ContactPerson,
        //                    AreaName = tinting.AreaName,
        //                    CityName = tinting.CityName,
        //                    ProvinceName = tinting.ProvinceName,
        //                    Address = tinting.Address,
        //                    Location = tinting.Location.ToString(CultureInfo.InvariantCulture),
        //                    DisplayArea = tinting.DisplayArea,
        //                    DispenseModel = tinting.TintingTypeName,
        //                    ShakerModel = tinting.Shaker,
        //                    PcModel = tinting.PCModel,
        //                    BuyMachineDeposit = tinting.BuyMachineDeposit,
        //                    TotalDeposit = tinting.TotalDeposit,
        //                    MachineDeposit = tinting.MachineDeposit,
        //                    DecorativeDeposit = tinting.DecorativeDeposit,
        //                    AuthID = tinting.CertiCode,
        //                    OpenDate = FormatDateTime(tinting.OpenDate),
        //                    RequestRemark = tinting.NewFitmentName.Contains("关店") ? "Close" : "Downgraded",
        //                    Process = taskFirstData.strProcessName,
        //                    Incident = incident,
        //                    ApplicationNO = applicationNo,
        //                    Step = taskFirstData.strStepName,
        //                    TaskID = taskFirstData.strTaskId,
        //                    StoreId = smdStore.StoreID,
        //                    MallName = tinting.StreetFullName,
        //                    MallShortName = tinting.StreetShortName,
        //                    HouseNumber = tinting.DoorNo,
        //                    EapproveSN = tinting.SerialNumber,
        //                    IsEapprove = true,
        //                    DeviceEapproveSN = tinting.SerialNumber,
        //                    StoreApprovedDate = tinting.HandleTime,
        //                    Channel = tinting.ShopTypeName.Contains("LIS") || tinting.ShopTypeName.Contains("LCSS") ? "来威" : "多乐士",
        //                    IsDowngraded = tinting.NewFitmentName.Contains("降级"),
        //                    IsRenew = false,
        //                    IsUpgraded = false,
        //                    BeforeDowngradedType = tinting.NewFitmentName.Contains("降级") ? tinting.ShopTypeName : "",
        //                    BusinessProcess = ass.BusinessProcess,
        //                    BusinessKey = ass.BusinessKey
        //                };

        //                conn.Execute(
        //                    "INSERT INTO t_StoreMasterData(SubmitDate,Creator,CreatorStaffCode,SerialNumber,DealerName,DealerCode,StoreType,StoreName,ApplicationType,NewFitment,Fax,Telephone,ContractPerson,AreaName,CityName,ProvinceName,Address,Location,DisplayArea,DispenseModel,ShakerModel,PcModel,BuyMachineDeposit,TotalDeposit,MachineDeposit,DecorativeDeposit,AuthID,OpenDate,RequestRemark,Process,Incident,ApplicationNO,Step,TaskID,EapproveSN,MallName,MallShortName,HouseNumber,Channel,IsEapprove,StoreId, DeviceEapproveSN, Status, StoreApprovedDate, IsUpgraded, IsDowngraded, IsRenew, BeforeUpgradedType, BeforeDowngradedType, BeforeRenewType,BusinessProcess,BusinessKey) " +
        //                    "VALUES(@SubmitDate,@Creator,@CreatorStaffCode,@SerialNumber,@DealerName,@DealerCode,@StoreType,@StoreName,@ApplicationType,@NewFitment,@Fax,@Telephone,@ContractPerson,@AreaName,@CityName,@ProvinceName,@Address,@Location,@DisplayArea,@DispenseModel,@ShakerModel,@PcModel,@BuyMachineDeposit,@TotalDeposit,@MachineDeposit,@DecorativeDeposit,@AuthID,@OpenDate,@RequestRemark,@Process,@Incident,@ApplicationNO,@Step,@TaskID,@EapproveSN,@MallName,@MallShortName,@HouseNumber,@Channel,@IsEapprove,@StoreId, @DeviceEapproveSN, 'E-approve导入无状态', @StoreApprovedDate, @IsUpgraded, @IsDowngraded, @IsRenew, @BeforeUpgradedType, @BeforeDowngradedType, @BeforeRenewType,@BusinessProcess,@BusinessKey)",
        //                    store, trans);

        //                #endregion
        //                BusinessService.SaveChildProcess(incident, "Store Data Change", ass, "active");
        //                var dealer = DealerService.GetByDealerCode(store.DealerCode);
        //                BusinessService.saveProcessRelation(incident, "Store Data Change", store, ass, smdStore, null, dealer, null, null, null, null);

        //                #region 变更日志

        //                var ocUser = TaskHelper.GetOcUser(winId);

        //                var changeLogs = new List<SmdChangeLog>();
        //                if (store.RequestRemark == "Close") //关店
        //                {
        //                    #region 关店
        //                    changeLogs.Add(
        //                        new SmdChangeLog
        //                        {
        //                            Category = "DegradeStore",
        //                            DataID = smdStore.StoreID.ToString(),
        //                            FieldName = "StoreStatus",
        //                            BeforeValue = smdStore.StoreStatus,
        //                            AfterValue = "关闭",
        //                            ChangeTime = DateTime.Now,
        //                            UserID = ocUser.strUserFullName,
        //                            AssessmentID = ass.ID
        //                        }
        //                        );


        //                    #endregion
        //                }
        //                else
        //                {
        //                    #region 降级

        //                    changeLogs.Add(
        //                        new SmdChangeLog
        //                        {
        //                            Category = "DegradeStore",
        //                            DataID = smdStore.StoreID.ToString(),
        //                            FieldName = "IsDowngraded",
        //                            BeforeValue = smdStore.IsDowngraded == null ? "" : smdStore.IsDowngraded.Value.ToString(),
        //                            AfterValue = "true",
        //                            ChangeTime = DateTime.Now,
        //                            UserID = ocUser.strUserFullName,
        //                            AssessmentID = ass.ID
        //                        }
        //                        );
        //                    changeLogs.Add(
        //                        new SmdChangeLog
        //                        {
        //                            Category = "DegradeStore",
        //                            DataID = smdStore.StoreID.ToString(),
        //                            FieldName = "BeforeDowngradedType",
        //                            BeforeValue = smdStore.BeforeDowngradedType,
        //                            AfterValue = smdStore.StoreType,
        //                            ChangeTime = DateTime.Now,
        //                            UserID = ocUser.strUserFullName,
        //                            AssessmentID = ass.ID
        //                        }
        //                        );
        //                    changeLogs.Add(
        //                        new SmdChangeLog
        //                        {
        //                            Category = "DegradeStore",
        //                            DataID = smdStore.StoreID.ToString(),
        //                            FieldName = "StoreType",
        //                            BeforeValue = smdStore.StoreType,
        //                            AfterValue = SmdStoreService.GetStoreTypeCode(tinting.ShopTypeName),
        //                            ChangeTime = DateTime.Now,
        //                            UserID = ocUser.strUserFullName,
        //                            AssessmentID = ass.ID
        //                        }
        //                        );

        //                    #endregion
        //                }

        //                changeLogs.Add(
        //                    new SmdChangeLog
        //                    {
        //                        Category = "DegradeStore",
        //                        DataID = smdStore.StoreID.ToString(),
        //                        FieldName = "CloseDate",
        //                        BeforeValue = smdStore.CloseDate == null ? "" : smdStore.CloseDate.ToString(),
        //                        AfterValue =
        //                            tinting.CloseDwnDate.HasValue
        //                                ? tinting.CloseDwnDate.Value.ToString("yyyy-MM-dd")
        //                                : DateTime.Now.ToString("yyyy-MM-dd"),
        //                        ChangeTime = DateTime.Now,
        //                        UserID = ocUser.strUserFullName,
        //                        AssessmentID = ass.ID
        //                    }
        //                    );
        //                changeLogs.Add(
        //                    new SmdChangeLog
        //                    {
        //                        Category = "DegradeStore",
        //                        DataID = smdStore.StoreID.ToString(),
        //                        FieldName = "CloseReason",
        //                        BeforeValue = smdStore.CloseReason,
        //                        AfterValue = tinting.RequestRemark,
        //                        ChangeTime = DateTime.Now,
        //                        UserID = ocUser.strUserFullName,
        //                        AssessmentID = ass.ID
        //                    }
        //                    );

        //                changeLogs.Add(
        //                    new SmdChangeLog
        //                    {
        //                        Category = "DegradeStore",
        //                        DataID = smdStore.StoreID.ToString(),
        //                        FieldName = "CloseType",
        //                        BeforeValue = smdStore.CloseType,
        //                        AfterValue = tinting.CloseReason,
        //                        ChangeTime = DateTime.Now,
        //                        UserID = ocUser.strUserFullName,
        //                        AssessmentID = ass.ID
        //                    }
        //                    );

        //                changeLogs.Add(
        //                    new SmdChangeLog
        //                    {
        //                        Category = "DegradeStore",
        //                        DataID = smdStore.StoreID.ToString(),
        //                        FieldName = "EapproveSN",
        //                        BeforeValue = smdStore.EapproveSN,
        //                        AfterValue = tinting.SerialNumber,
        //                        ChangeTime = DateTime.Now,
        //                        UserID = ocUser.strUserFullName,
        //                        AssessmentID = ass.ID
        //                    }
        //                    );

        //                changeLogs.Add(
        //                    new SmdChangeLog
        //                    {
        //                        Category = "DegradeStore",
        //                        DataID = smdStore.StoreID.ToString(),
        //                        FieldName = "StoreApprovedDate",
        //                        BeforeValue = smdStore.StoreApprovedDate == null ? "" : smdStore.StoreApprovedDate.ToString(),
        //                        AfterValue = tinting.HandleTime.ToString(),
        //                        ChangeTime = DateTime.Now,
        //                        UserID = ocUser.strUserFullName,
        //                        AssessmentID = ass.ID
        //                    }
        //                    );

        //                conn.Execute(
        //                    "INSERT INTO t_StoreDataChangeLog(Category,DataID,FieldName,ChangeReason,BeforeValue,AfterValue,ChangeTime,UserID,AssessmentID) " +
        //                    "VALUES (@Category,@DataID,@FieldName,@ChangeReason,@BeforeValue,@AfterValue,@ChangeTime,@UserID,@AssessmentID)",
        //                    changeLogs, trans
        //                    );



        //                #endregion

        //                trans.Commit();
        //                Logger.Debug(tinting.NewFitmentName + "成功！");
        //            }
        //            catch (Exception ex)
        //            {
        //                trans.Rollback();
        //                Logger.Debug(tinting.NewFitmentName + "失败！");
        //                Logger.Error(ex);

        //                //如果业务数据写入失败，删除相关流程实例
        //                TaskHelper.DeleteIncident("Store Data Change", incident, winId);
        //            }
        //        }

        //        #endregion


        //    }

        //    /// <summary>
        //    /// 新门店
        //    /// </summary>
        //    /// <param name="tinting"></param>
        //    public void NewStore(Tinting tinting)
        //    {
        //        var variables = new List<Variable>();
        //        var applicationNo = "";
        //        var incident = 0;
        //        var winId = GetWinId(tinting.CreatorEmpDN);
        //        if (tinting.CertiCode != null
        //            && !string.IsNullOrEmpty(tinting.CertiCode)
        //            && !tinting.CertiCode.StartsWith("A")
        //            && tinting.CertiCode.Length == 8)
        //            tinting.CertiCode = "A" + tinting.CertiCode;
        //        //流程步骤执行人
        //        variables.AddRange(MdcRecipientService.SetNewStoreRecipient(tinting.ProvinceName, tinting.AreaName));
        //        var rAssignAuthID = variables.Find(t => t.strVariableName == "R_Assign_AuthID");

        //        var arrUserName = new string[1] 
        //    {
        //        rAssignAuthID.objVariableValue[0].ToString()
        //    };

        //        variables.Add("StoreName", tinting.ShopName);
        //        variables.Add("StoreType", tinting.ShopTypeName);
        //        variables.Add("StoreAddress", tinting.Address);
        //        variables.Add("IsEapprove", "EApprove发起");
        //        variables.Add("AutoBusinessKey", "Store");
        //        variables.Add("SerialNumber", tinting.SerialNumber);
        //        variables.Add("NewFitment", tinting.NewFitmentName);

        //        incident = TaskHelper.NewIncident(winId, "New Store Application",
        //            "发放授权号 / 门店-" + tinting.ShopName + " ( " + tinting.NewFitmentName + ")", variables, out applicationNo);


        //        #region 绑定业务数据

        //        if (incident == 0) //流程发起失败
        //        {
        //            return;
        //        }

        //        var taskAssignAuthId = TaskHelper.GetTask("New Store Application", incident, arrUserName, "Assign AuthID");

        //        using (var conn = SqlConnectionHelper.GetConnection(Constant.MDC_DB_NAME))
        //        {
        //            var trans = conn.BeginTransaction();
        //            try
        //            {

        //                var ass = TaskHelper.SetAssessment(winId, taskAssignAuthId.strProcessName, incident,
        //                    "Fill in the request", "Store", conn, trans);

        //                var storeTypeCode = SmdStoreService.GetStoreTypeCode(tinting.ShopTypeName);

        //                var store = new Store
        //                {
        //                    SubmitDate = tinting.SubmitDate,
        //                    Creator = winId,
        //                    CreatorStaffCode = tinting.CreatorEmpCode,
        //                    SerialNumber = tinting.SerialNumber,
        //                    DealerName = tinting.CustomerName,
        //                    DealerCode = tinting.CustomerCode,
        //                    StoreType = storeTypeCode,
        //                    StoreName = tinting.ShopName,
        //                    ApplicationType = tinting.ApplicationTypeName,
        //                    NewFitment = tinting.NewFitmentName,
        //                    Fax = tinting.Fax,
        //                    Telephone = tinting.Telephone,
        //                    ContractPerson = tinting.ContactPerson,
        //                    AreaName = tinting.AreaName,
        //                    CityName = tinting.CityName,
        //                    ProvinceName = tinting.ProvinceName,
        //                    Address = tinting.Address,
        //                    Location = tinting.Location.ToString(CultureInfo.InvariantCulture),
        //                    DisplayArea = tinting.DisplayArea,
        //                    DispenseModel = tinting.TintingTypeName,
        //                    ShakerModel = tinting.Shaker,
        //                    PcModel = tinting.PCModel,
        //                    BuyMachineDeposit = tinting.BuyMachineDeposit,
        //                    TotalDeposit = tinting.TotalDeposit,
        //                    MachineDeposit = tinting.MachineDeposit,
        //                    DecorativeDeposit = tinting.DecorativeDeposit,
        //                    AuthID = tinting.CertiCode,
        //                    OpenDate = FormatDateTime(tinting.OpenDate),
        //                    Process = taskAssignAuthId.strProcessName,
        //                    Incident = incident,
        //                    ApplicationNO = applicationNo,
        //                    Step = taskAssignAuthId.strStepName,
        //                    TaskID = taskAssignAuthId.strTaskId,
        //                    StoreId = 0,
        //                    MallName = tinting.StreetFullName,
        //                    MallShortName = tinting.StreetShortName,
        //                    HouseNumber = tinting.DoorNo,
        //                    EapproveSN = tinting.SerialNumber,
        //                    IsEapprove = true,
        //                    DeviceEapproveSN = tinting.SerialNumber,
        //                    StoreApprovedDate = tinting.HandleTime,
        //                    Channel = storeTypeCode == "LIS" || storeTypeCode == "LCSS" ? "来威" : "多乐士",
        //                    IsDowngraded = false,

        //                    BusinessKey = ass.BusinessKey,
        //                    BusinessProcess = ass.BusinessProcess
        //                };

        //                SmdStoreService.FormatBeforeType(tinting, store);


        //                conn.Execute(
        //                    "INSERT INTO t_StoreMasterData(SubmitDate,Creator,CreatorStaffCode,SerialNumber,DealerName,DealerCode,StoreType,StoreName,ApplicationType,NewFitment,Fax,Telephone,ContractPerson,AreaName,CityName,ProvinceName,Address,Location,DisplayArea,DispenseModel,ShakerModel,PcModel,BuyMachineDeposit,TotalDeposit,MachineDeposit,DecorativeDeposit,AuthID,OpenDate,RequestRemark,Process,Incident,ApplicationNO,Step,TaskID,EapproveSN,MallName,MallShortName,HouseNumber,Channel, IsEapprove, DeviceEapproveSN, Status, StoreApprovedDate,IsUpgraded, IsDowngraded, IsRenew, BeforeUpgradedType, BeforeDowngradedType, BeforeRenewType, LastRenewDate, BusinessProcess, BusinessKey) " +
        //                    "VALUES(@SubmitDate,@Creator,@CreatorStaffCode,@SerialNumber,@DealerName,@DealerCode,@StoreType,@StoreName,@ApplicationType,@NewFitment,@Fax,@Telephone,@ContractPerson,@AreaName,@CityName,@ProvinceName,@Address,@Location,@DisplayArea,@DispenseModel,@ShakerModel,@PcModel,@BuyMachineDeposit,@TotalDeposit,@MachineDeposit,@DecorativeDeposit,@AuthID,@OpenDate,@RequestRemark,@Process,@Incident,@ApplicationNO,@Step,@TaskID,@EapproveSN,@MallName,@MallShortName,@HouseNumber,@Channel, @IsEapprove, @DeviceEapproveSN, 'E-approve导入无状态', @StoreApprovedDate, @IsUpgraded, @IsDowngraded, @IsRenew, @BeforeUpgradedType, @BeforeDowngradedType, @BeforeRenewType, @LastRenewDate, @BusinessProcess, @BusinessKey)",
        //                    store, trans);



        //                trans.Commit();
        //                Logger.Debug(tinting.NewFitmentName + "成功！");
        //                BusinessService.SaveChildProcess(incident, "New Store Application", ass, "active");
        //                var dealer = DealerService.GetByDealerCode(store.DealerCode);
        //                var smdstore = new SmdStore
        //                {
        //                    AuthID = store.AuthID,
        //                    StoreName = store.StoreName,
        //                    StoreAddress = store.Address,
        //                    StoreApprovedDate = store.StoreApprovedDate,
        //                    StoreStatus = "E-approve导入无状态",
        //                    StoreType = store.StoreType,
        //                    EapproveSN = store.SerialNumber,
        //                    Region = store.AreaName,
        //                    Province = store.ProvinceName,
        //                    CityName = store.CityName
        //                };

        //                if (store.NewFitment == "翻新")
        //                {
        //                    smdstore.StoreStatus = "营业";
        //                }
        //                BusinessService.saveProcessRelation(incident, "New Store Application", store, ass, smdstore, null, dealer, null, null, null, null);

        //            }
        //            catch (Exception ex)
        //            {
        //                trans.Rollback();
        //                Logger.Debug(tinting.NewFitmentName + "失败！");
        //                Logger.Error(ex);
        //                //业务数据写入失败，需要删除发起的流程实例
        //                TaskHelper.DeleteIncident("New Store Application", incident, winId);
        //            }




        //        #endregion
        //        }

        //    }

        //#endregion

        #region  Update By Tony 2016/3/17
        public override void ExecuteTask(IJobExecutionContext context)
        {

            AssessmentService.GetLastLikeKey("NS");
            //1.从E-Approve数据库中抓取新审批通过的数据。
            //var tintings = TintingService.GetList();

            //1.从SMD同步表里面抓取CRM传过来的数据 --Add By Tony 20160413
            var syncList = SyncPoolService.GetList();

            using (var conn = SqlConnectionHelper.GetConnection(Constant.MDC_DB_NAME))
            {
                foreach (var syncModel in syncList)
                {

                    //syncModel.ProvinceName = syncModel.ProvinceName.Replace("省", "").Replace("市", "").Replace("自治区", "");
                    if (!string.IsNullOrEmpty(syncModel.SubDealerCode))
                    {
                        var subDealer = DealerService.GetByDealerCode(syncModel.SubDealerCode);
                        if (subDealer != null)
                        {
                            syncModel.SubDealerName = subDealer.Name;
                        }
                    }
                    //格式化省份格式，去掉“省”，“市”， “自治区”
                    if (!string.IsNullOrEmpty(syncModel.ProvinceName))
                    {
                        syncModel.ProvinceName = syncModel.ProvinceName.Replace("省", "").Replace("市", "").Replace("自治区", "");

                        //2.根据不同的申请类型发起不同的流程
                        if (syncModel.NewFitmentName.Contains("关店") || syncModel.NewFitmentName.Contains("降级")) //发起主数据变更流程
                        {
                            if (string.IsNullOrEmpty(syncModel.CertiCode)) //授权号不能为空
                            {
                                Logger.Debug("授权号不能为空！[" + syncModel.ShopName + syncModel.InstanceGuid + "]");
                                continue;
                            }

                            DegradeStore(syncModel);
                        }
                        else //发起新门店流程
                        {
                            if (syncModel.ApplicationTypeName == "无需机器" && Double.Parse(syncModel.MachineDeposit) > 0)
                            {
                                Logger.Debug("[" + syncModel.SerialNumber + "]的申请类型为“无需机器”，但是设备保证金金额为" +
                                             syncModel.MachineDeposit);
                                continue;
                            }
                            NewStore(syncModel);
                        }
                        Logger.Debug("省份区域信息为空！[" + syncModel.AutoID + syncModel.StoreName + syncModel.SerialNumber + "]");
                        continue;
                    }
                }

            }
        }

        /// <summary>
        ///  申请人WinId转换 EApprove中的格式是
        ///  cn=dengj11,cn=organizational users,o=AkzoNobel,cn=cordys,o=apac.ad.ici.com，
        ///  需要转换成 apac.ad.ici.com/dengj11
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public string GetWinId(string code)
        {
            const string defaultAccount = "d30.intra/svc_dpcna_mdc";
            //const string defaultAccount = "d30.intra/wangc21";
            if (string.IsNullOrEmpty(code)) //发起人不能为空
            {
                return defaultAccount;
            }
            try
            {
                var arrStrings = code.Split(',');
                var winId = arrStrings[arrStrings.Length - 1].Split('=')[1] + '/' + arrStrings[0].Split('=')[1];

                //查询OC里面有没有此帐号
                var oc = new OrgChart();
                User ocUser;

                return (oc.FindUser(winId, "", 0, out ocUser)) ? winId : defaultAccount;
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                return defaultAccount;
            }
        }

        /// <summary>
        /// 门店降级关闭
        /// </summary>
        /// <param name="tinting"></param>
        public void DegradeStore(SyncPoolModel tinting)
        {
            tinting = GetStoreMasterData(tinting);

            var variables = new List<Variable>();
            var applicationNo = "";
            var incident = 0;
            var winId = GetWinId(tinting.CreatorEmpDN);

            // 匹配EP与SMD中的授权号命名规则
            if (!tinting.CertiCode.StartsWith("A")) tinting.CertiCode = "A" + tinting.CertiCode;

            var smdStore = SmdStoreService.GetByAuthId(tinting.CertiCode);
            if (smdStore == null)
            {
                Logger.Debug("授权号错误，找不到相应门店数据！[" + tinting.CertiCode + "]");
                return;
            }

            //发起流程
            variables.AddRange(MdcRecipientService.SetStoreDataChangeRecipient(tinting.AreaName, tinting.ProvinceName, "Store"));
            variables.Add("BlankVlue", smdStore.StoreID);
            variables.Add("Actions", "DegradeStore");
            variables.Add("AutoBusinessKey", "DegradeStore");
            variables.Add("MailSubject", smdStore.StoreName);


            incident = TaskHelper.NewIncident(winId, "Store Data Change",
                tinting.NewFitmentName + " - " + tinting.ShopName, variables, out applicationNo);

            //获取first Task
            var taskFirstData = TaskHelper.GetTask("Store Data Change", incident, new[] { winId }, "Fill in the request");

            #region 绑定业务数据

            if (incident == 0 || taskFirstData == null) //流程发起失败
            {
                Logger.Debug("主数据变更流程发起失败！[" + tinting.InstanceGuid + "]");
                return;
            }

            using (var conn = SqlConnectionHelper.GetConnection(Constant.MDC_DB_NAME))
            {
                var trans = conn.BeginTransaction();
                try
                {
                    #region  写入业务数据

                    var ass = TaskHelper.SetAssessment(winId, taskFirstData.strProcessName, incident,
                        taskFirstData.strStepName, "DegradeStore", conn, trans);

                    var storeTypeCode = SmdStoreService.GetStoreTypeCode(tinting.ShopTypeName);
                    double dbuymachine = 0;
                    double damount = 0;
                    try
                    {
                        dbuymachine = Double.Parse(tinting.BuyMachineDeposit);
                    }
                    catch
                    {

                    }
                    try
                    {
                        damount = Double.Parse(tinting.Amount);
                    }
                    catch
                    {

                    }
                    var store = new Store
                    {
                        SubmitDate = tinting.SubmitDate,
                        Creator = winId,
                        CreatorStaffCode = tinting.CreatorEmpCode,
                        SerialNumber = tinting.SerialNumber,
                        DealerName = tinting.CustomerName,
                        DealerCode = tinting.CustomerCode,
                        StoreType = storeTypeCode,
                        StoreName = tinting.ShopName,
                        ApplicationType = tinting.ApplicationTypeName,
                        NewFitment = tinting.NewFitmentName,
                        Fax = tinting.Fax,
                        Telephone = tinting.Telephone,
                        ContractPerson = tinting.ContactPerson,
                        AreaName = tinting.AreaName,
                        CityName = tinting.CityName,
                        ProvinceName = tinting.ProvinceName,
                        Address = tinting.Address,
                        //Location = tinting.Location.ToString(CultureInfo.InvariantCulture),
                        DisplayArea = tinting.DisplayArea,
                        DispenseModel = tinting.TintingTypeName,
                        ShakerModel = tinting.Shaker,
                        PcModel = tinting.PCModel,
                        BuyMachineDeposit = tinting.BuyMachineDeposit,
                        TotalDeposit = (dbuymachine + damount).ToString(),
                        MachineDeposit = tinting.MachineDeposit,
                        DecorativeDeposit = tinting.DecorativeDeposit,
                        AuthID = tinting.CertiCode,
                        OpenDate = FormatDateTime(tinting.OpenDate),
                        RequestRemark = tinting.NewFitmentName.Contains("关店") ? "Close" : "Downgraded",
                        Process = taskFirstData.strProcessName,
                        Incident = incident,
                        ApplicationNO = applicationNo,
                        Step = taskFirstData.strStepName,
                        TaskID = taskFirstData.strTaskId,
                        StoreId = smdStore.StoreID,
                        MallName = tinting.StreetFullName,
                        MallShortName = tinting.StreetShortName,
                        HouseNumber = tinting.HouseNumber,
                        EapproveSN = tinting.SerialNumber,
                        IsEapprove = true,
                        DeviceEapproveSN = tinting.SerialNumber,
                        StoreApprovedDate = tinting.StoreApprovedDate,
                        Channel = tinting.ShopTypeName.Contains("LIS") || tinting.ShopTypeName.Contains("LCSS") ? "来威" : "多乐士",
                        IsDowngraded = tinting.NewFitmentName.Contains("降级"),
                        IsRenew = false,
                        IsUpgraded = false,
                        BeforeDowngradedType = tinting.NewFitmentName.Contains("降级") ? tinting.ShopTypeName : "",
                        BusinessProcess = ass.BusinessProcess,
                        BusinessKey = ass.BusinessKey,

                        //Add By Tony 20160413
                        OwnerType = (!string.IsNullOrEmpty(tinting.SubDealerCode) || !string.IsNullOrEmpty(tinting.SubDealerName)) ? 2 : 1,
                        District = tinting.District,
                        BMCCode = tinting.BMCCode,
                        BMCName = tinting.BMCName,
                        SubDealerCode = tinting.SubDealerCode,
                        SubDealerName = tinting.SubDealerName,
                        AccountOwner = tinting.AccountOwner,
                        WechatId = tinting.WechatId,
                        IsTransferMachine = tinting.IsTransferMachine,
                        CustomerDevice = tinting.CustomerDevice,
                        Lat = tinting.Lat,
                        Lon = tinting.Lon,
                        //Add By Yanxiang
                        ShopSeq = tinting.ShopSeq,
                    };

                    string sqlStr = SyncPoolService.GetSMDInsertSql(store);

                    //updated by Tony 20160413
                    conn.Execute(sqlStr, store, trans);

                    //conn.Execute(
                    //    "INSERT INTO t_StoreMasterData(SubmitDate,Creator,CreatorStaffCode,SerialNumber,DealerName,DealerCode,StoreType,StoreName,ApplicationType,NewFitment,Fax,Telephone,ContractPerson,AreaName,CityName,ProvinceName,Address,Location,DisplayArea,DispenseModel,ShakerModel,PcModel,BuyMachineDeposit,TotalDeposit,MachineDeposit,DecorativeDeposit,AuthID,OpenDate,RequestRemark,Process,Incident,ApplicationNO,Step,TaskID,EapproveSN,MallName,MallShortName,HouseNumber,Channel,IsEapprove,StoreId, DeviceEapproveSN, Status, StoreApprovedDate, IsUpgraded, IsDowngraded, IsRenew, BeforeUpgradedType, BeforeDowngradedType, BeforeRenewType,BusinessProcess,BusinessKey) " +
                    //    "VALUES(@SubmitDate,@Creator,@CreatorStaffCode,@SerialNumber,@DealerName,@DealerCode,@StoreType,@StoreName,@ApplicationType,@NewFitment,@Fax,@Telephone,@ContractPerson,@AreaName,@CityName,@ProvinceName,@Address,@Location,@DisplayArea,@DispenseModel,@ShakerModel,@PcModel,@BuyMachineDeposit,@TotalDeposit,@MachineDeposit,@DecorativeDeposit,@AuthID,@OpenDate,@RequestRemark,@Process,@Incident,@ApplicationNO,@Step,@TaskID,@EapproveSN,@MallName,@MallShortName,@HouseNumber,@Channel,@IsEapprove,@StoreId, @DeviceEapproveSN, 'E-approve导入无状态', @StoreApprovedDate, @IsUpgraded, @IsDowngraded, @IsRenew, @BeforeUpgradedType, @BeforeDowngradedType, @BeforeRenewType,@BusinessProcess,@BusinessKey)",
                    //    store, trans);

                    #endregion
                    BusinessService.SaveChildProcess(incident, "Store Data Change", ass, "active");
                    var dealer = DealerService.GetByDealerCode(store.DealerCode);
                    BusinessService.saveProcessRelation(incident, "Store Data Change", store, ass, smdStore, null, dealer, null, null, null, null);

                    #region 变更日志

                    var ocUser = TaskHelper.GetOcUser(winId);

                    var changeLogs = new List<SmdChangeLog>();


                    #region 添加 ChangeLog

                    if (store.RequestRemark == "Close") //关店
                    {
                        #region 关店
                        changeLogs.Add(
                            new SmdChangeLog
                            {
                                Category = "DegradeStore",
                                DataID = smdStore.StoreID.ToString(),
                                FieldName = "StoreStatus",
                                BeforeValue = smdStore.StoreStatus,
                                AfterValue = "关闭",
                                ChangeTime = DateTime.Now,
                                UserID = ocUser.strUserFullName,
                                AssessmentID = ass.ID
                            }
                            );

                        changeLogs.Add(
                            new SmdChangeLog
                            {
                                Category = "DegradeStore",
                                DataID = smdStore.StoreID.ToString(),
                                FieldName = "CloseReason",
                                BeforeValue = smdStore.CloseReason,
                                AfterValue = tinting.CloseReason,
                                ChangeTime = DateTime.Now,
                                UserID = ocUser.strUserFullName,
                                AssessmentID = ass.ID
                            }
                            );

                        changeLogs.Add(
                            new SmdChangeLog
                            {
                                Category = "DegradeStore",
                                DataID = smdStore.StoreID.ToString(),
                                FieldName = "CloseType",
                                BeforeValue = smdStore.CloseType,
                                AfterValue = tinting.CloseType,
                                ChangeTime = DateTime.Now,
                                UserID = ocUser.strUserFullName,
                                AssessmentID = ass.ID
                            });
                        #endregion
                    }
                    else
                    {
                        #region 降级

                        changeLogs.Add(
                            new SmdChangeLog
                            {
                                Category = "DegradeStore",
                                DataID = smdStore.StoreID.ToString(),
                                FieldName = "IsDowngraded",
                                BeforeValue = smdStore.IsDowngraded == null ? "" : smdStore.IsDowngraded.Value.ToString(),
                                AfterValue = "true",
                                ChangeTime = DateTime.Now,
                                UserID = ocUser.strUserFullName,
                                AssessmentID = ass.ID
                            }
                            );
                        changeLogs.Add(
                            new SmdChangeLog
                            {
                                Category = "DegradeStore",
                                DataID = smdStore.StoreID.ToString(),
                                FieldName = "BeforeDowngradedType",
                                BeforeValue = smdStore.BeforeDowngradedType,
                                AfterValue = smdStore.StoreType,
                                ChangeTime = DateTime.Now,
                                UserID = ocUser.strUserFullName,
                                AssessmentID = ass.ID
                            }
                            );
                        changeLogs.Add(
                            new SmdChangeLog
                            {
                                Category = "DegradeStore",
                                DataID = smdStore.StoreID.ToString(),
                                FieldName = "StoreType",
                                BeforeValue = smdStore.StoreType,
                                AfterValue = SmdStoreService.GetStoreTypeCode(tinting.ShopTypeName),
                                ChangeTime = DateTime.Now,
                                UserID = ocUser.strUserFullName,
                                AssessmentID = ass.ID
                            }
                            );

                        #endregion
                    }
                    changeLogs.Add(
                        new SmdChangeLog
                        {
                            Category = "DegradeStore",
                            DataID = smdStore.StoreID.ToString(),
                            FieldName = "CloseDate",
                            BeforeValue = smdStore.CloseDate == null ? "" : smdStore.CloseDate.ToString(),
                            AfterValue =
                                ParseDateTime(tinting.CloseDate).HasValue
                                    ? ParseDateTime(tinting.CloseDate).Value.ToString("yyyy-MM-dd")
                                    : DateTime.Now.ToString("yyyy-MM-dd"),
                            ChangeTime = DateTime.Now,
                            UserID = ocUser.strUserFullName,
                            AssessmentID = ass.ID
                        }
                        );
                    changeLogs.Add(
                        new SmdChangeLog
                        {
                            Category = "DegradeStore",
                            DataID = smdStore.StoreID.ToString(),
                            FieldName = "CloseReason",
                            BeforeValue = smdStore.CloseReason,
                            AfterValue = tinting.CloseReason,
                            ChangeTime = DateTime.Now,
                            UserID = ocUser.strUserFullName,
                            AssessmentID = ass.ID
                        }
                        );

                    changeLogs.Add(
                        new SmdChangeLog
                        {
                            Category = "DegradeStore",
                            DataID = smdStore.StoreID.ToString(),
                            FieldName = "CloseType",
                            BeforeValue = smdStore.CloseType,
                            AfterValue = tinting.CloseType,
                            ChangeTime = DateTime.Now,
                            UserID = ocUser.strUserFullName,
                            AssessmentID = ass.ID
                        }
                        );

                    changeLogs.Add(
                        new SmdChangeLog
                        {
                            Category = "DegradeStore",
                            DataID = smdStore.StoreID.ToString(),
                            FieldName = "EapproveSN",
                            BeforeValue = smdStore.EapproveSN,
                            AfterValue = tinting.SerialNumber,
                            ChangeTime = DateTime.Now,
                            UserID = ocUser.strUserFullName,
                            AssessmentID = ass.ID
                        }
                        );

                    changeLogs.Add(
                        new SmdChangeLog
                        {
                            Category = "DegradeStore",
                            DataID = smdStore.StoreID.ToString(),
                            FieldName = "StoreApprovedDate",
                            BeforeValue = smdStore.StoreApprovedDate == null ? "" : smdStore.StoreApprovedDate.ToString(),
                            AfterValue = DateTime.Now.ToString("yyyy-MM-dd"),
                            ChangeTime = DateTime.Now,
                            UserID = ocUser.strUserFullName,
                            AssessmentID = ass.ID
                        }
                        );
                    #endregion

                    conn.Execute(
                        "INSERT INTO t_StoreDataChangeLog(Category,DataID,FieldName,ChangeReason,BeforeValue,AfterValue,ChangeTime,UserID,AssessmentID) " +
                        "VALUES (@Category,@DataID,@FieldName,@ChangeReason,@BeforeValue,@AfterValue,@ChangeTime,@UserID,@AssessmentID)",
                        changeLogs, trans
                        );



                    #endregion

                    trans.Commit();
                    Logger.Debug(tinting.NewFitmentName + "成功！");
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    Logger.Debug(tinting.NewFitmentName + "失败！");
                    Logger.Error(ex);

                    //如果业务数据写入失败，删除相关流程实例
                    TaskHelper.DeleteIncident("Store Data Change", incident, winId);
                }
            }

            #endregion


        }

        /// <summary>
        /// 新门店
        /// </summary>
        /// <param name="tinting"></param>
        public void NewStore(SyncPoolModel tinting)
        {
            tinting = GetStoreMasterData(tinting);
            var variables = new List<Variable>();
            var applicationNo = "";
            var incident = 0;
            var winId = GetWinId(tinting.CreatorEmpDN);
            if (tinting.CertiCode != null
                && !string.IsNullOrEmpty(tinting.CertiCode)
                && !tinting.CertiCode.StartsWith("A")
                && tinting.CertiCode.Length == 8)
                tinting.CertiCode = "A" + tinting.CertiCode;
            //流程步骤执行人
            variables.AddRange(MdcRecipientService.SetNewStoreRecipient(tinting.ProvinceName, tinting.AreaName));
            var rAssignAuthID = variables.Find(t => t.strVariableName == "R_Assign_AuthID");

            var arrUserName = new string[1] 
            {
                rAssignAuthID.objVariableValue[0].ToString()
            };

            variables.Add("StoreName", tinting.ShopName);
            variables.Add("StoreType", tinting.ShopTypeName);
            variables.Add("StoreAddress", tinting.Address);
            variables.Add("IsEapprove", "CRM发起");
            variables.Add("AutoBusinessKey", "Store");
            variables.Add("SerialNumber", tinting.SerialNumber);
            variables.Add("NewFitment", tinting.NewFitmentName);

            incident = TaskHelper.NewIncident(winId, "New Store Application",
                "发放授权号 / 门店-" + tinting.ShopName + " ( " + tinting.NewFitmentName + ")", variables, out applicationNo);


            #region 绑定业务数据

            if (incident == 0) //流程发起失败
            {
                return;
            }

            var taskAssignAuthId = TaskHelper.GetTask("New Store Application", incident, arrUserName, "Assign AuthID");

            using (var conn = SqlConnectionHelper.GetConnection(Constant.MDC_DB_NAME))
            {
                var trans = conn.BeginTransaction();
                try
                {

                    var ass = TaskHelper.SetAssessment(winId, taskAssignAuthId.strProcessName, incident,
                        "Fill in the request", "Store", conn, trans);

                    var storeTypeCode = SmdStoreService.GetStoreTypeCode(tinting.ShopTypeName);
                    double dbuymachine = 0;
                    double damount = 0;
                    try
                    {
                        dbuymachine = Double.Parse(tinting.BuyMachineDeposit);
                    }
                    catch
                    {

                    }
                    try
                    {
                        damount = Double.Parse(tinting.Amount);
                    }
                    catch
                    {

                    }
                    var store = new Store
                    {
                        SubmitDate = tinting.SubmitDate,
                        Creator = winId,
                        CreatorStaffCode = tinting.CreatorEmpCode,
                        SerialNumber = tinting.SerialNumber,
                        DealerName = tinting.CustomerName,
                        DealerCode = tinting.CustomerCode,
                        StoreType = storeTypeCode,
                        StoreName = tinting.ShopName,
                        ApplicationType = tinting.ApplicationTypeName,
                        NewFitment = tinting.NewFitmentName,
                        Fax = tinting.Fax,
                        Telephone = tinting.Telephone,
                        ContractPerson = tinting.ContactPerson,
                        AreaName = tinting.AreaName,
                        CityName = tinting.CityName,
                        ProvinceName = tinting.ProvinceName,
                        Address = tinting.Address,
                        //Location = tinting.Location.ToString(CultureInfo.InvariantCulture),
                        DisplayArea = tinting.DisplayArea,
                        DispenseModel = tinting.TintingTypeName,
                        ShakerModel = tinting.Shaker,
                        PcModel = tinting.PCModel,
                        BuyMachineDeposit = tinting.BuyMachineDeposit,

                        TotalDeposit = (dbuymachine + damount).ToString(),
                        MachineDeposit = tinting.Amount,
                        DecorativeDeposit = tinting.DecorativeDeposit,
                        AuthID = tinting.CertiCode,
                        OpenDate = FormatDateTime(tinting.OpenDate),
                        Process = taskAssignAuthId.strProcessName,
                        Incident = incident,
                        ApplicationNO = applicationNo,
                        Step = taskAssignAuthId.strStepName,
                        TaskID = taskAssignAuthId.strTaskId,
                        StoreId = 0,
                        MallName = tinting.StreetFullName,
                        MallShortName = tinting.StreetShortName,
                        HouseNumber = tinting.HouseNumber,
                        EapproveSN = tinting.SerialNumber,
                        IsEapprove = true,
                        DeviceEapproveSN = tinting.SerialNumber,
                        StoreApprovedDate = tinting.StoreApprovedDate,
                        Channel = storeTypeCode == "LIS" || storeTypeCode == "LCSS" ? "来威" : "多乐士",
                        IsDowngraded = false,

                        //Add By Tony 20160413
                        OwnerType = (!string.IsNullOrEmpty(tinting.SubDealerCode) || !string.IsNullOrEmpty(tinting.SubDealerName)) ? 2 : 1,
                        District = tinting.District,
                        BMCCode = tinting.BMCCode,
                        BMCName = tinting.BMCName,
                        SubDealerCode = tinting.SubDealerCode,
                        SubDealerName = tinting.SubDealerName,
                        AccountOwner = tinting.AccountOwner,
                        WechatId = tinting.WechatId,
                        IsTransferMachine = tinting.IsTransferMachine,
                        CustomerDevice = tinting.CustomerDevice,
                        //Add By Yanxiang
                        ShopSeq = tinting.ShopSeq,
                        BusinessKey = ass.BusinessKey,
                        BusinessProcess = ass.BusinessProcess,
                        Lat = tinting.Lat,
                        Lon = tinting.Lon,

                        Status = tinting.Status,
                        CurrentStartDate = tinting.CurrentStartDate
                    };

                    SmdStoreService.FormatBeforeType(tinting, store);

                    string sqlStr = SyncPoolService.GetSMDInsertSql(store);

                    //updated by Tony 20160413
                    conn.Execute(sqlStr, store, trans);

                    //conn.Execute(
                    //    "INSERT INTO t_StoreMasterData(SubmitDate,Creator,CreatorStaffCode,SerialNumber,DealerName,DealerCode,StoreType,StoreName,ApplicationType,NewFitment,Fax,Telephone,ContractPerson,AreaName,CityName,ProvinceName,Address,Location,DisplayArea,DispenseModel,ShakerModel,PcModel,BuyMachineDeposit,TotalDeposit,MachineDeposit,DecorativeDeposit,AuthID,OpenDate,RequestRemark,Process,Incident,ApplicationNO,Step,TaskID,EapproveSN,MallName,MallShortName,HouseNumber,Channel, IsEapprove, DeviceEapproveSN, Status, StoreApprovedDate,IsUpgraded, IsDowngraded, IsRenew, BeforeUpgradedType, BeforeDowngradedType, BeforeRenewType, LastRenewDate, BusinessProcess, BusinessKey) " +
                    //    "VALUES(@SubmitDate,@Creator,@CreatorStaffCode,@SerialNumber,@DealerName,@DealerCode,@StoreType,@StoreName,@ApplicationType,@NewFitment,@Fax,@Telephone,@ContractPerson,@AreaName,@CityName,@ProvinceName,@Address,@Location,@DisplayArea,@DispenseModel,@ShakerModel,@PcModel,@BuyMachineDeposit,@TotalDeposit,@MachineDeposit,@DecorativeDeposit,@AuthID,@OpenDate,@RequestRemark,@Process,@Incident,@ApplicationNO,@Step,@TaskID,@EapproveSN,@MallName,@MallShortName,@HouseNumber,@Channel, @IsEapprove, @DeviceEapproveSN, 'E-approve导入无状态', @StoreApprovedDate, @IsUpgraded, @IsDowngraded, @IsRenew, @BeforeUpgradedType, @BeforeDowngradedType, @BeforeRenewType, @LastRenewDate, @BusinessProcess, @BusinessKey)",
                    //    store, trans);



                    trans.Commit();
                    Logger.Debug(tinting.NewFitmentName + "成功！");
                    BusinessService.SaveChildProcess(incident, "New Store Application", ass, "active");
                    var dealer = DealerService.GetByDealerCode(store.DealerCode);
                    var smdstore = new SmdStore
                    {
                        AuthID = store.AuthID,
                        StoreName = store.StoreName,
                        StoreAddress = store.Address,
                        StoreApprovedDate = store.StoreApprovedDate,
                        StoreStatus = store.Status,
                        StoreType = store.StoreType,
                        EapproveSN = store.SerialNumber,
                        Region = store.AreaName,
                        Province = store.ProvinceName,
                        CityName = store.CityName,

                        //Add By Tony 20160413
                        District = store.District,
                        WechatId = store.WechatId,
                        AccountOwner = store.AccountOwner,
                        BMCCode = store.BMCCode,
                        BMCName = store.BMCName,
                        //Add By Yanxiang 20170228
                        StoreSize = (tinting.StoreSize == null ? 0 : Decimal.Parse(tinting.StoreSize.ToString())),
                        Channel = store.Channel,
                        ContactPerson = store.ContractPerson,

                    };

                    if (store.NewFitment == "翻新")
                    {
                        smdstore.StoreStatus = "营业";
                    }
                    BusinessService.saveProcessRelation(incident, "New Store Application", store, ass, smdstore, null, dealer, null, null, null, null);

                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    Logger.Debug(tinting.NewFitmentName + "失败！");
                    Logger.Error(ex);
                    //业务数据写入失败，需要删除发起的流程实例
                    TaskHelper.DeleteIncident("New Store Application", incident, winId);
                }

            #endregion
            }

        }
        #endregion

        #region 新门店不取CRM传过来的值
        public SyncPoolModel GetStoreMasterData(SyncPoolModel tinting)
        {
            if (!string.IsNullOrEmpty(tinting.CertiCode))
            {
                StoreMaster store = StoreMasterService.GetStoreMasterDataByAuthId(tinting.CertiCode);
                if (store != null)
                {
                    tinting.Address = store.StoreAddress;
                    tinting.CityName = store.CityName;
                    tinting.ContactPerson = store.ContactPerson;
                    //tinting.ShopTypeName = store.StoreType;
                    tinting.DisplayArea = Double.Parse(store.StoreSize.ToString());
                    tinting.OpenDate = store.FirstStartDate;
                    tinting.ProvinceName = store.Province;
                    //tinting.ShopTypeCode = store.StoreType;
                    tinting.StreetFullName = store.MallName;
                    tinting.StreetShortName = store.MallShortName;
                    tinting.Telephone = store.PhoneNumber;
                    tinting.District = store.District;
                    tinting.Lat = store.Lat;
                    tinting.Lon = store.Lon;

                    tinting.BMCCode = store.BMCCode;
                    tinting.BMCName = store.BMCName;

                    tinting.SubDealerCode = store.SubDealerCode;
                    tinting.SubDealerName = store.SubDealerName;
                    tinting.WechatId = store.WechatId;
                    tinting.AccountOwner = store.AccountOwner;
                    tinting.StoreName = store.StoreName;
                    tinting.ShopName = store.StoreName;
                    tinting.ShopSeq = store.ShopSeq;
                    tinting.HouseNumber = store.HouseNumber;
                    tinting.StoreApprovedDate = DateTime.Now;
                    tinting.Status = store.StoreStatus;
                    tinting.CurrentStartDate = store.CurrentStartDate;
                }
            }
            else
            {
                tinting.Status = "CRM导入无状态";
            }
            return tinting;
        }
        #endregion
    }
}
